#include "HttpClients/HttpGlobalResource.hpp"
#include <mutex>
#include <curl/curl.h>

using namespace CppWinApi::HttpClients;

std::atomic<int> HttpGlobalResource::resourceCount = 0;
std::mutex HttpGlobalResource::counterMutex;

void HttpGlobalResource::InitResource()
{
    if (resourceCount.load(std::memory_order_acquire) < 1)
    {
        std::lock_guard<std::mutex> lock(HttpGlobalResource::counterMutex);
        if (resourceCount.load(std::memory_order_relaxed) == 0)
        {
            curl_global_init(CURL_GLOBAL_ALL);
            resourceCount.store(1, std::memory_order_release);
        }
    }
    resourceCount.fetch_add(1, std::memory_order_relaxed);
}

void HttpGlobalResource::ReleaseResource()
{
    // 先快速检查是否需要处理（避免不必要的锁）
    if (resourceCount.load(std::memory_order_acquire) == 0)
    {
        return; // 计数器已为0，直接返回
    }

    std::lock_guard<std::mutex> lock(counterMutex);
    // 再次检查（双重检查锁定模式）
    if (resourceCount.load(std::memory_order_relaxed) > 0)
    {
        // 原子递减并获取递减后的值
        int newCount = resourceCount.fetch_sub(1, std::memory_order_release) - 1;
        if (newCount == 0)
        {
            curl_global_cleanup(); // 仅当计数器归零时清理
        }
    }
}